const WXAPI = require('apifm-wxapi')
const AUTH = require('../../utils/auth')
import WxValidate from "../../utils/WxValidate";
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    defAvatar: '/images/defAvatar.png',
    companyInfo: undefined,
    newLists: undefined,
    solutionLists: undefined,
    wxlogin: true,
    cardUserInfo: undefined,
    kActionType: {},
    content: '...',
    qrcode: undefined,
    isExpandAll: false,
    // statusBarHeight: app.globalData.statusBarHeight,
    // titleBarHeight: app.globalData.titleBarHeight,
    favoriteNum: 0,
    favoriteStatus: 0,
    userId: undefined,
    companyId: undefined,
    hasToken: wx.getStorageSync('appToken'),
    applyStatus: undefined,
    noPassMsg: undefined,
    errorObj: {},
    tabBarList: [{
        id: 1,
        pagePath: "/pages/card/main",
        iconPath: "/images/v1/add.png",
        activePath: "/images/v1/add-active.png",
        text: "添加通讯录"
      },
      {
        id: 2,
        pagePath: "/pages/complain/main",
        iconPath: "/images/v1/complain.png",
        activePath: "/images/v1/complain-active.png",
        text: "投诉建议"
      },
      {
        id: 3,
        pagePath: "/pages/card/main",
        iconPath: "/images/v1/service2.svg",
        activePath: "/images/v1/share-active.png",
        text: '智能助手'
      },
      {
        id: 4,
        pagePath: "/pages/policy/main",
        iconPath: "/images/v1/policy.png",
        activePath: "/images/v1/policy-active.png",
        text: "政策宣传"
      },
      {
        id: 5,
        pagePath: "/pages/notice/main",
        iconPath: "/images/v1/notice.png",
        activePath: "/images/v1/notice-active.png",
        text: "通知公告"
      },

    ],
    color: "rgb(195,194,203)",
    selectedColor: "rgb(0, 131, 255)",
    isApplyAgain: false,
    phoneNumber: undefined
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(e) {
    // console.log('other-card:',e);
    //获取url参数
    this.setData({
      userId: e.userId,
      companyId: e.companyId
    })
    this.initValidate();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    //判断是否本人名片，true时跳转首页
    if (this.data.userId == wx.getStorageSync('userId')) {
      wx.switchTab({
        url: '/pages/card/main',
      })
      return
    }
    this.setData({
      isApplyAgain: false
    })
    //判断是否登录，true检查白名单，false返回首页登录，登陆后跳转当前名片
    if (wx.getStorageSync('phoneNumber')) {
      this.setData({
        phoneNumber: wx.getStorageSync('phoneNumber')
      })
      this.checkCardCustomerOwnerStatus()
    } else {
      wx.showModal({
        title: '未登录',
        content: "请返回首页登录后重试",
        showCancel: false,
        confirmText: '返回首页',
        success: () => {
          wx.setStorageSync('backUrl', '/pages/other-card/main?userId=' + this.data.userId + '&companyId=' + this.data.companyId)
          wx.switchTab({
            url: '/pages/card/main'
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //分享名片
  onShareAppMessage: function () {
    // return {
    //   title: '您好，我是 ' + wx.getStorageSync('mallName') + ' 的' + this.data.cardUserInfo.base.nick + '，请惠存我的名片。',
    //   path: '/pages/card/main?cardUid=' + this.data.cardUserInfo.base.id,
    //   imageUrl: this.data.cardUserInfo.base.avatarUrl
    // }
  },
  //跳转备用名片
  goStandby() {
    wx.navigateTo({
      url: '/pages/standby-switch/main?userId=' + this.data.cardUserInfo.user.userId,
    })
  },
  //获取广告图
  getBanner(id) {
    let data = {
      companyId: id
    }
    // if (wx.getStorageSync('companyId')) {
    //   data.companyId = wx.getStorageSync('companyId')
    // }
    WXAPI.getBanner(data).then(res => {
      // console.log(res);
      if (res.code == 200) {
        this.setData({
          bannerList: res.data
        })
      } else {
        this.setData({
          bannerList: []
        })
      }
    }).catch(err => {
      console.log(err);
      this.setData({
        bannerList: []
      })
    })
  },
  //初始化表单验证
  initValidate() {
    let rules = {
      userName: {
        required: true,
        maxlength: 20
      },
      // phoneNum: {
      //   required: true,
      //   tel: true
      // },
      idCard: {
        required: false,
        idcard: true
      },
      address: {
        required: false,
        maxlength: 100
      },

    }

    let message = {
      userName: {
        required: '请输入姓名',
        maxlength: '名字不能超过20个字'
      },
      // phoneNum: {
      //   required: "请输入手机号码",
      //   tel: '请输入11位的手机号码'
      // },
      idCard: {
        required: "请输入身份证号码",
        idcard: "请输入正确的身份证号码"
      },

      address: {
        required: "请输入地址",
        maxlength: "地址不能超过100个字"
      },
    }
    //实例化当前的验证规则和提示消息
    this.WxValidate = new WxValidate(rules, message);
  },
  //提交白名单申请
  formSubmit(e) {
    // console.log('formSubmit', e.detail.value)
    let params = e.detail.value;
    for (const key in params) {
      params[key] = params[key].trim()
    }
    if (!this.WxValidate.checkForm(params)) {
      let error = this.WxValidate.errorList;
      let errorObj = {}
      for (const key of error) {
        errorObj[key.param] = key.msg
      }
      console.log(error);
      this.setData({
        errorObj: errorObj
      })
      return false;
    }
    this.setData({
      errorObj: {}
    })
    params.companyId = this.data.companyId
    params.phoneNum = this.data.noPassMsg?.phoneNum || this.data.phoneNumber
    console.log(params);
    if (this.data.isApplyAgain) {
      WXAPI.reApply(params).then(res => {
        console.log('reApply',res);
        if (res.code == 200) {
          this.checkCardCustomerOwnerStatus()
        } else {
          wx.showModal({
            title: '提交失败',
            content: res.msg,
            showCancel: false,
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showModal({
          title: '提交失败',
          content: '请重试',
          showCancel: false,
        })
      })
    } else {
      WXAPI.apply(params).then(res => {
        console.log('apply',res);
        if (res.code == 200) {
          this.checkCardCustomerOwnerStatus()
        } else {
          wx.showModal({
            title: '提交失败',
            content: res.msg,
            showCancel: false,
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showModal({
          title: '提交失败',
          content: '请重试',
          showCancel: false,
        })
      })
    }

  },
  //重置表单
  formReset(e) {
    // console.log('form发生了reset事件，携带数据为：', e.detail.value)
    this.setData({
      chosen: ''
    })
  },
  //重新申请
  applyAgain() {
    this.setData({
      applyStatus: 501,
      isApplyAgain: true
    })
  },
  //检查是否白名单及申请状态
  checkCardCustomerOwnerStatus() {
    //检查用户身份，Waiter直接获取名片信息，Customer检查白名单状态
    if (wx.getStorageSync('appToken') && wx.getStorageSync('miniAppRole') == 'Waiter') {
      this.getUserInfo()
    } else {
      WXAPI.getCardCustomerOwnerStatus(wx.getStorageSync('phoneNumber')).then(res => {
        if (res.code == 200) { //有白名单信息
          wx.setStorageSync('appToken', res.data.appToken)
          wx.setStorageSync('companyId', res.data.companyId)
          if (res.data.companyId == this.data.companyId) { //名片与白名单匹配，获取名片信息
            this.getUserInfo()
          } else { //不匹配则提示
            //返回首页
            if (getCurrentPages().length <= 1) {
              wx.showModal({
                title: '没有访问权限',
                content: "您已绑定其它公司，如需访问，请先联系管理员解除绑定",
                showCancel: false,
                confirmText: '返回首页',
                success() {
                  wx.switchTab({
                    url: '/pages/card/main',
                  })
                }
              })
            } else {
              //返回上一页
              wx.showModal({
                title: '没有访问权限',
                content: "您已绑定其它公司，如需访问，请先接联系管理员解除绑定",
                showCancel: false,
                confirmText: '返回',
                success() {
                  wx.navigateBack()
                }
              })
            }
          }
        } else if (res.code == 501) { //没有白名单权限
          this.setData({
            applyStatus: 501
          })
        } else if (res.code == 502) { //申请中
          this.setData({
            applyStatus: 502
          })
        } else if (res.code == 503) { //审核不通过
          this.setData({
            applyStatus: 503,
            noPassMsg: res.data.customerOwner
          })
        } else {
          wx.showToast({
            title: '加载失败',
            icon: 'error'
          })
        }
      }).catch(err => {
        console.log(err);
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        })
      })
    }

  },
  //获取访问的名片信息
  getUserInfo() {
    WXAPI.getVisitCard(this.data.userId).then((res) => {
      // WXAPI.getVisitCard(1).then((res) => {
      console.log('getUserInfo:', res,this.data.userId)
      if (res.code === 200) {
        this.setData({
          cardUserInfo: res.data,
        })
        this.getCompanyDif(res.data.company.id)
        this.getBanner(res.data.company.id)
        wx.setStorageSync('cardUserInfo', res.data)
        wx.setNavigationBarTitle({
          title: res.data.user.userName + '的名片'
        })
      } else {
        if (res.code == 501) {
          this.setData({
            applyStatus: 501
          })
        } else if (res.code == 502) {
          this.setData({
            applyStatus: 502
          })
        } else if (res.code == 503) {
          this.setData({
            applyStatus: 503,
            noPassMsg: res.data.customerOwner
          })
        } else if (res.code == 504) {
          //访问的名片不存在 白名单不匹配
          if (getCurrentPages().length <= 1) {
            if (res.msg === '访问的名片不存在') {
              wx.showModal({
                title: '名片不存在',
                content: "您访问的名片已失效",
                showCancel: false,
                confirmText: '返回首页',
                success() {
                  wx.switchTab({
                    url: '/pages/card/main',
                  })
                }
              })
            } else {
              wx.showModal({
                title: '没有访问权限',
                content: "您已绑定其它公司，如需访问，请先接联系管理员解除绑定",
                showCancel: false,
                confirmText: '返回首页',
                success() {
                  wx.switchTab({
                    url: '/pages/card/main',
                  })
                }
              })
            }

          } else {
            if (res.msg === '访问的名片不存在') {
              wx.showModal({
                title: '名片不存在',
                content: "您访问的名片已失效",
                showCancel: false,
                confirmText: '返回',
                success() {
                  wx.navigateBack()
                }
              })
            } else {
              wx.showModal({
                title: '没有访问权限',
                content: "您已绑定其它公司，如需访问，请先接联系管理员解除绑定",
                showCancel: false,
                confirmText: '返回',
                success() {
                  wx.navigateBack()
                }
              })
            }
            
          }
        } else {
          wx.showToast({
            title: '加载失败',
            icon: 'error'
          })
        }
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    })
  },
  //获取通知政策公司信息
  getCompanyDif(id) {
    WXAPI.getCompanyDif({
      cardCompanyId: id,
      pageNum: 1,
      pageSize: 3,
      type: 1
    }).then(res => {
      if (res.code == 200) {
        this.setData({
          newLists: res.data.list
        })
      } else {
        this.setData({
          newLists: []
        })
      }
    }).catch(err => {
      this.setData({
        newLists: []
      })
    })
    WXAPI.getCompanyDif({
      cardCompanyId: id,
      pageNum: 1,
      pageSize: 3,
      type: 2
    }).then(res => {

      if (res.code == 200) {
        this.setData({
          solutionLists: res.data.list
        })
      } else {
        this.setData({
          solutionLists: []
        })
      }
    }).catch(err => {
      this.setData({
        solutionLists: []
      })
    })
    WXAPI.getCompanyDif({
      cardCompanyId: id,
      pageNum: 1,
      pageSize: 1,
      type: 3
    }).then(res => {
      if (res.code == 200) {
        this.setData({
          companyInfo: res.data.list[0] || false
        })
      } else {
        this.setData({
          companyInfo: []
        })
      }
    }).catch(err => {
      this.setData({
        companyInfo: []
      })
    })
  },
  //复制信息
  copyData(e) {
    const v = e.currentTarget.dataset.v
    wx.setClipboardData({
      data: v,
      success: (res) => {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        })
      }
    })
  },
  //添加通信录
  addPhoneContact() {
    //添加到通讯录
    wx.addPhoneContact({
      photoFilePath: this.data.cardUserInfo.base.avatarUrl,
      organization: wx.getStorageSync('mallName'),
      title: this.data.cardUserInfo.ext['职位'],
      firstName: this.data.cardUserInfo.base.nick,
      mobilePhoneNumber: this.data.cardUserInfo.base.mobile
    })
  },
  //展开公司信息
  expandAll() {
    this.setData({
      isExpandAll: !this.data.isExpandAll
    })
  },
  //展开个人信息
  expandAllUserInfo() {
    this.setData({
      isExpandUserInfo: !this.data.isExpandUserInfo
    })
  },
  //tab切换
  switchTab(e) {
    const data = e.currentTarget.dataset
    const url = data.path + '?id=' + this.data.cardUserInfo.company.id
    this.setData({
      selected: data.index
    })
    if (data.index == 1) {
      wx.addPhoneContact({
        firstName: this.data.cardUserInfo.user.userName,
        mobilePhoneNumber: this.data.cardUserInfo.user.phoneNumber,
        organization: this.data.cardUserInfo.company.name,
        email: this.data.cardUserInfo.user.email,
        title: this.data.cardUserInfo.user.companyPosition,
        success: (res) => {
          // console.log('addPhoneContactSuccess：', res);
        },
        fail: (err) => {
          console.log('addPhoneContactErr：', err);
        }
      })
    } else if (data.index == 2) {
      this.setData({
        selected: data.index
      })
      let suggestionLink = encodeURIComponent(this.data.cardUserInfo.company.suggestionLink)
      wx.navigateTo({
        url: '/pages/complain/main?suggestionLink=' + suggestionLink
      })

    } else if (data.index == 3) {
      this.goOutUrl()
    } else if (data.index == 4 || data.index == 5) {
      this.setData({
        selected: data.index
      })
      // console.log(url);
      wx.navigateTo({
        url: url
      })
    }
  },
  //预览图片
  previewImage: function (e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      // current: current, // 当前显示图片的http链接  
      urls: [current] // 需要预览的图片http链接列表  
    })
  },
  //跳转详情页
  goDetail(e) {
    wx.navigateTo({
      url: '/pages/news-detail/main?news=' + JSON.stringify(e.currentTarget.dataset.news)
    })
  },
  goAd(e) {
    let url = encodeURIComponent(e.currentTarget.dataset.url)
    if (url && url.length) {
      wx.navigateTo({
        url: '/pages/ad/main?adUrl=' + url
      })
    }
  },
  //跳转客服
  goOutUrl: function (e) {
    let url = encodeURIComponent(this.data.cardUserInfo.company.echoLink)
    wx.navigateTo({
      url: '/pages/out/main?echoLink=' + url
    })
  },
})